package com.xbongbong.saas.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.constant.MessageConstant;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.field.ItemPoJo;
import com.xbongbong.paas.pojo.vo.PaasFormDataEsListVO;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.RegexUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.paas.util.ExplainUtil;
import com.xbongbong.paas.util.ItemUtil;
import com.xbongbong.pro.businessdata.pojo.dto.BusinessContactListRelyDTO;
import com.xbongbong.pro.businessdata.pojo.vo.BusinessContactListRelyVO;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.weblist.pojo.SaasAnalysisDataFieldPojo;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.domain.entity.WorkOrderExplainEntity;
import com.xbongbong.saas.domain.entity.ext.ContactEntityExt;
import com.xbongbong.saas.domain.entity.ext.CustomerEntityExt;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.ContactEnum;
import com.xbongbong.saas.enums.business.CustomerManagementEnum;
import com.xbongbong.saas.model.ContactModel;
import com.xbongbong.saas.model.CustomerModel;
import com.xbongbong.saas.model.WorkOrderExplainModel;
import com.xbongbong.saas.service.BusinessContactService;
import com.xbongbong.saas.service.toolbox.help.AnalysisSaasDataListHelp;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

import static com.xbongbong.saas.help.ProDetailHandlerHelp.LOG;

/**
 *
 * @author 刘阳
 * @date 2019/11/11 5:24 PM
 * @since v1.0
 * @version v1.0
 */
@Service("BusinessContactService")
public class BusinessContactServiceImpl implements BusinessContactService {

    @Resource
    private CustomerModel customerModel;
    @Resource
    private ContactModel contactModel;
    @Resource
    private WorkOrderExplainModel workOrderExplainModel;
    @Resource
    private AnalysisSaasDataListHelp analysisSaasDataListHelp;

    @Override
    public BusinessContactListRelyVO businessContactListGetRely(BusinessContactListRelyDTO businessContactListRelyDTO) throws XbbException{
        String corpid = businessContactListRelyDTO.getCorpid();
        Long refId = businessContactListRelyDTO.getDataId();
        Long formId = businessContactListRelyDTO.getFormId();
        BusinessContactListRelyVO businessContactListRelyVO = new BusinessContactListRelyVO();
        //新建的单据
        XbbRefTypeEnum xbbRefTypeEnum = XbbRefTypeEnum.getByCode(businessContactListRelyDTO.getBusinessType());
        switch (xbbRefTypeEnum) {
            case WORK_ORDER:
                WorkOrderExplainEntity workOrderExplainEntity = workOrderExplainModel.getByFormId(formId, corpid);
                if (workOrderExplainEntity == null || workOrderExplainEntity.getDel() == 1) {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_EXPLAIN_NOT_EXIST);
                }
                //  获取字段解释信息，并且过滤不可见字段 start
                List<FieldAttrEntity> explainList = JSONArray.parseArray(workOrderExplainEntity.getExplains(), FieldAttrEntity.class);
                Map<String, FieldAttrEntity> explainMap = new HashMap<>(explainList.size());
                for (FieldAttrEntity fieldAttrEntity : explainList) {
                    explainMap.put(fieldAttrEntity.getAttr(), fieldAttrEntity);
                }
                PaasFormDataEntityExt paasFormDataEsEntity = new PaasFormDataEntityExt();
                PaasFormDataEsListVO paasFormDataEsListVO = new PaasFormDataEsListVO();
                List<PaasFormDataEntityExt> formDataEsEntities = new ArrayList<>();
                if (Objects.equals(businessContactListRelyDTO.getRefBusinessType(), XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode())) {
                    CustomerEntityExt customerEntityExt = customerModel.getByKey(refId, corpid);
                    JSONObject data = customerEntityExt.getData();
                    BeanUtil.copyProperties(customerEntityExt, paasFormDataEsEntity);
                    paasFormDataEsEntity.setData(data);
                    formDataEsEntities.add(paasFormDataEsEntity);
                    paasFormDataEsListVO.setPaasFormDataESList(formDataEsEntities);
                    SaasAnalysisDataFieldPojo saasAnalysisDataFieldPojo = analysisSaasDataListHelp.packageDataField(explainMap, paasFormDataEsListVO.getBusinessType());
                    if (Objects.nonNull(data.getJSONArray(ContactEnum.PHONE.getAttr()))) {
                        businessContactListRelyVO.setContactArray(analysisPhoneHelp(data, explainMap, CustomerManagementEnum.PHONE.getAttr(), saasAnalysisDataFieldPojo));
                    }
                } else if (Objects.equals(businessContactListRelyDTO.getRefBusinessType(), XbbRefTypeEnum.CONTACT.getCode())) {
                    ContactEntityExt contactEntityExt = contactModel.getByKey(refId, corpid);
                    JSONObject data = contactEntityExt.getData();
                    BeanUtil.copyProperties(contactEntityExt, paasFormDataEsEntity);
                    paasFormDataEsEntity.setData(data);
                    formDataEsEntities.add(paasFormDataEsEntity);
                    paasFormDataEsListVO.setPaasFormDataESList(formDataEsEntities);
                    SaasAnalysisDataFieldPojo saasAnalysisDataFieldPojo = analysisSaasDataListHelp.packageDataField(explainMap, paasFormDataEsListVO.getBusinessType());
                    if (Objects.nonNull(data.getJSONArray(ContactEnum.PHONE.getAttr()))) {
                        businessContactListRelyVO.setContactArray(analysisPhoneHelp(data, explainMap, ContactEnum.PHONE.getAttr(), saasAnalysisDataFieldPojo));
                    }
                }
                break;
            default:
                break;
        }

        return businessContactListRelyVO;
     }

    /**
     * Description: 解析联系电话
     * @param data
     * @return JSONArray
     * @author 刘阳
     * @date 2019/11/18 2:17 PM
     * @since v1.0
     */
    private JSONArray analysisPhoneHelp(JSONObject data, Map<String, FieldAttrEntity> explainMap, String attr, SaasAnalysisDataFieldPojo saasAnalysisDataFieldPojo) {
        for (Map.Entry<String, Map<String, String>> entry : saasAnalysisDataFieldPojo.getCombMap().entrySet()) {
            //字段值
            String key = Objects.toString(entry.getKey());
            if (key.contains(StringConstant.POINT)) {
                //子表单
                try {
                    List<String> keyList = StringUtil.toStringList(key, "\\.");
                    if (keyList == null || keyList.isEmpty()) {
                        continue;
                    }
                    FieldAttrEntity fieldAttrEntity = explainMap.get(keyList.get(0));
                    Map<String, FieldAttrEntity> subExplainMap = ExplainUtil.getExplainMap(JSON.toJSONString(fieldAttrEntity.getSubForm().getItems()), null);
                    JSONArray subForm = data.getJSONArray(keyList.get(0));
                    if (Objects.isNull(subForm)) {
                        continue;
                    }
                    for (Object obj : subForm) {
                        JSONObject json = (JSONObject) obj;
                        // 子表单中内字段
                        String subAttr = keyList.get(1);
                        FieldAttrEntity subField = subExplainMap.get(subAttr);
                        List<ItemPoJo> itemPoJos = subField.getItems();
                        Map<String, ItemPoJo> itemMap = new HashMap<>(itemPoJos.size());
                        Set<String> textSet = new HashSet<>();
                        itemPoJos.forEach(item->{
                            itemMap.put(item.getValue().toString(), item);
                            textSet.add(item.getText());
                        });
                        JSONObject result = new JSONObject();
                        if (Objects.nonNull(json.get(subAttr))) {
                            Object value = json.get(subAttr);
                            if (StringUtil.isEmpty(value.toString())){
                                result.put("text", "");
                                result.put("value", "");
                            }
                            ItemPoJo itemPoJo = itemMap.get(value.toString());
                            if (Objects.nonNull(itemPoJo)) {
                                result.put("text", itemPoJo.getText());
                                result.put("value", itemPoJo.getValue());

                            }  else if ((ItemUtil.isUUID(value.toString()) || RegexUtil.isOnePositiveInt(value.toString())) && Objects.equals(fieldAttrEntity.getIsRedundant(), 0)) {
                                // 如果是uuId，则应该是已经被删了的下拉框
                                result.put("text", "");
                                result.put("value", "");
                            } else {
                                result.put("text", "");
                                result.put("value", value.toString());
                            }
                        } else {
                            result = null;
                        }
                        json.put(keyList.get(1), result);
                    }
                    data.put(keyList.get(0), subForm);
                } catch (Exception e) {
                    //出错不做任何处理
                    LOG.error("",e);
                }
            }
        }
        return data.getJSONArray(attr);
    }

}
